import err from '../common/error.js'

import routes from './routes.js'

const routerUtils = {
  // 处理传递的参数
  solveParams (params) {
    let tail = ''
    if (params && typeof params === 'object') {
      tail = tail + '?'
      for (let key in params) {
        let data = JSON.stringify(params[key])
        data = encodeURIComponent(data)
        tail = tail + key + '=' + data + '&'
      }
      tail = tail.slice(0, -1)
    }
    return tail
  },
  
  // 解析获取的参数
  analyseData (data) {
    let result = {}
    if (data && typeof data === 'object') {
      for (let key in data) {
        let obj = decodeURIComponent(data[key])
        obj = JSON.parse(obj)
        result[key] = obj
      }      
    }
    return result
  },
  
  // 保留当前页面，前进，只能在应用中跳转
  push (name = '', params = {}) {
    return new Promise((resolve, reject) => {
      const path = routes[name]
      if (!path) {
        reject(err('ROUTE_NO_EXISTS'))
      }
      const url = path + routerUtils.solveParams(params)
      uni.navigateTo({
        url: url,
        success: (res) => {
          resolve()
        },
        fail: (e) => {
          reject(err('ROUTE_FAILED', e))
        }
      })      
    })

  }
}

export default routerUtils